package com.dataart.training.crimequalification.beans;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * Validates phone number according to E.164 standard.
 */
@FacesValidator("e164PhoneNumberValidator")
public class E164PhoneNumberValidator implements Validator {

    //-----------------------------------------------------------------------

    private static final String ANY_REGION = "ZZ";
    private static final String UK_COUNTRY_CODE = "GB";

    //-----------------------------------------------------------------------

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        String phoneNumber = value.toString();
        PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
        try {
            phoneNumberUtil.parse(phoneNumber, ANY_REGION);
        } catch (NumberParseException e) {
            Phonenumber.PhoneNumber exampleNumber = phoneNumberUtil.getExampleNumber(UK_COUNTRY_CODE);
            FacesMessage msg =
                    new FacesMessage("Phone number validation failed.",
                            "Invalid number format. Here's an example: +" + exampleNumber.getCountryCode() +
                                    exampleNumber.getNationalNumber());
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
}
